"""
固件下载模型 - PyQt5版本
管理固件下载相关的状态和进度，使用Qt信号机制
"""
from PyQt5.QtCore import QObject, pyqtSignal
from typing import List
from dataclasses import dataclass
from enum import Enum

class DownloadStatus(Enum):
    """下载状态枚举"""
    IDLE = "idle"                   # 空闲状态
    LOADING_FIRMWARE = "loading"    # 加载固件中
    CONNECTING = "connecting"       # 连接中
    DOWNLOADING = "downloading"     # 下载中
    COMPLETED = "completed"         # 下载完成
    FAILED = "failed"              # 下载失败
    CANCELLED = "cancelled"        # 下载取消

@dataclass
class DownloadProgress:
    """下载进度数据类"""
    percentage: float = 0.0         # 进度百分比 (0.0-100.0)
    message: str = ""               # 当前操作消息
    status: DownloadStatus = DownloadStatus.IDLE  # 下载状态

@dataclass
class FirmwareInfo:
    """固件信息数据类"""
    file_path: str = ""             # 固件文件路径
    file_name: str = ""             # 固件文件名
    file_size: int = 0              # 文件大小（字节）
    checksum: str = ""              # 校验和
    version: str = ""               # 版本信息
    is_loaded: bool = False         # 是否已加载

class DownloadModel(QObject):
    """下载模型类 - 基于QObject，支持信号发射"""
    
    # 定义信号
    progress_changed = pyqtSignal(DownloadProgress)     # 进度变化信号
    status_changed = pyqtSignal(DownloadStatus)         # 状态变化信号
    log_added = pyqtSignal(str)                         # 日志添加信号
    firmware_info_changed = pyqtSignal(FirmwareInfo)    # 固件信息变化信号
    
    def __init__(self, parent=None):
        """初始化下载模型
        
        Args:
            parent: 父对象
        """
        super().__init__(parent)
        self._progress = DownloadProgress()
        self._firmware_info = FirmwareInfo()
        self._download_log: List[str] = []
        self._max_log_lines = 1000  # 最大日志行数
    
    def get_progress(self) -> DownloadProgress:
        """获取当前进度
        
        Returns:
            DownloadProgress: 当前下载进度
        """
        return self._progress
    
    def update_progress(self, percentage: float, message: str = "") -> None:
        """更新下载进度
        
        Args:
            percentage: 进度百分比
            message: 进度消息
        """
        self._progress.percentage = max(0.0, min(100.0, percentage))
        if message:
            self._progress.message = message
        self.progress_changed.emit(self._progress)
    
    def set_status(self, status: DownloadStatus, message: str = "") -> None:
        """设置下载状态
        
        Args:
            status: 下载状态
            message: 状态消息
        """
        self._progress.status = status
        if message:
            self._progress.message = message
        self.status_changed.emit(status)
        self.progress_changed.emit(self._progress)
    
    def get_firmware_info(self) -> FirmwareInfo:
        """获取固件信息
        
        Returns:
            FirmwareInfo: 固件信息
        """
        return self._firmware_info
    
    def set_firmware_info(self, file_path: str, file_name: str = "",
                         file_size: int = 0, checksum: str = "",
                         version: str = "") -> None:
        """设置固件信息
        
        Args:
            file_path: 固件文件路径
            file_name: 固件文件名
            file_size: 文件大小
            checksum: 校验和
            version: 版本信息
        """
        self._firmware_info.file_path = file_path
        self._firmware_info.file_name = file_name or file_path.split('/')[-1]
        self._firmware_info.file_size = file_size
        self._firmware_info.checksum = checksum
        self._firmware_info.version = version
        self._firmware_info.is_loaded = bool(file_path)
        self.firmware_info_changed.emit(self._firmware_info)
    
    def clear_firmware_info(self) -> None:
        """清空固件信息"""
        self._firmware_info = FirmwareInfo()
        self.firmware_info_changed.emit(self._firmware_info)
    
    def add_log(self, message: str) -> None:
        """添加日志消息
        
        Args:
            message: 日志消息
        """
        self._download_log.append(message)
        
        # 限制日志行数
        if len(self._download_log) > self._max_log_lines:
            self._download_log = self._download_log[-self._max_log_lines:]
        
        self.log_added.emit(message)
    
    def get_logs(self) -> List[str]:
        """获取所有日志
        
        Returns:
            List[str]: 日志消息列表
        """
        return self._download_log.copy()
    
    def clear_logs(self) -> None:
        """清空日志"""
        self._download_log.clear()
    
    def reset(self) -> None:
        """重置下载状态"""
        self._progress = DownloadProgress()
        self.clear_logs()
        # 保留固件信息，只重置状态
    

    
    def is_ready_for_download(self) -> bool:
        """检查是否准备好下载
        
        Returns:
            bool: 是否可以开始下载
        """
        return (
            self._firmware_info.is_loaded and
            self._progress.status in [DownloadStatus.IDLE, DownloadStatus.COMPLETED, DownloadStatus.FAILED]
        )